import {
  Image,
  StyleSheet,
  TouchableOpacity,
  View,
  Dimensions,
  ScrollView,
  TextInput,
  LayoutAnimation
} from 'react-native'
import React, { useEffect, useMemo, useState } from 'react'
import { reqArticleDetail } from '@/api/article'
import { RouteProp, useNavigation, useRoute } from '@react-navigation/native'
import type { ResArticleDetail } from '@/types/article'
import { Text } from 'react-native-paper'
import Carousel from 'react-native-reanimated-carousel'
import HeartAnimated from '@/components/HeartAnimated'
import { userStore } from '@/store/user'
import { observer } from 'mobx-react-lite'

import icon_arrow from '@/assets/images/icon_arrow.png'
import icon_share from '@/assets/images/icon_share.png'
import icon_edit_comment from '@/assets/images/icon_edit_comment.png'
import icon_collection from '@/assets/images/icon_collection.png'
import icon_collection_selected from '@/assets/images/icon_collection_selected.png'
import icon_comment from '@/assets/images/icon_comment.png'
import Comment from './components/Comment'
import { StackNavigationProp } from '@react-navigation/stack'

const Article = observer(() => {
  // 获取屏幕宽度
  const width = Dimensions.get('window').width
  const { params } = useRoute<RouteProp<any>>()
  // 存储文章详情
  const [articleDetail, setArticleDetail] = useState<ResArticleDetail>()
  // 存储评论详情
  const comment = useMemo(() => {
    return articleDetail?.comments
  }, [articleDetail])
  // 获取文章详情
  const getArticleDetail = async () => {
    const res = await reqArticleDetail(params!.id)
    setArticleDetail(res)
  }
  useEffect(() => {
    getArticleDetail()
  }, [])

  // 当前激活项索引
  const [activeIndex, setActiveIndex] = useState(0)
  // 轮播图切换的回调
  const onScrollEnd = (index: number) => {
    setActiveIndex(index)
  }

  // 输入框动画属性

  // 控制底部右侧图标容器是否显示
  const [footerRightShow, setFooterRightShow] = useState(true)
  // 输入框获得焦点的回调
  const onFocus = () => {
    LayoutAnimation.easeInEaseOut()
    setFooterRightShow(false)
  }
  // 输入框失去焦点的回调
  const onBlur = () => {
    LayoutAnimation.easeInEaseOut()
    setFooterRightShow(true)
  }
  const navigation = useNavigation<StackNavigationProp<any>>()
  // 点击头部返回的回调
  const onGoBack = () => {
    navigation.goBack()
  }
  return (
    <View style={styles.container}>
      {/* 头部 */}
      <View style={styles.header}>
        {/* 返回 */}
        <TouchableOpacity onPress={onGoBack} activeOpacity={0.7}>
          <Image source={icon_arrow} style={styles.iconArrow}></Image>
        </TouchableOpacity>
        {/* 用户名和头像 */}
        <TouchableOpacity style={styles.nameAvatarLayout}>
          <Image source={{ uri: articleDetail?.avatarUrl }} style={styles.avatar}></Image>
          <Text style={styles.username}>{articleDetail?.userName}</Text>
        </TouchableOpacity>
        {/* 关注 */}
        <TouchableOpacity style={styles.followBtn} activeOpacity={0.7}>
          <Text style={styles.followTxt}>关注</Text>
        </TouchableOpacity>
        {/* 分享 */}
        <TouchableOpacity activeOpacity={0.7}>
          <Image source={icon_share} style={styles.iconShare}></Image>
        </TouchableOpacity>
      </View>
      <ScrollView>
        {/* 轮播图 */}
        <View>
          <Carousel
            width={width}
            height={540}
            data={articleDetail?.images!}
            onScrollEnd={onScrollEnd}
            // @ts-ignore
            renderItem={({ item }) => (
              <View style={styles.swiperContainer}>
                <Image source={{ uri: item }} style={styles.imageView}></Image>
              </View>
            )}
          ></Carousel>
          {/* 右上角当前页标识 */}
          {articleDetail?.images && (
            <View style={styles.pageBox}>
              <Text style={styles.pageTxt}>{`${activeIndex + 1}/${articleDetail?.images
                .length}`}</Text>
            </View>
          )}

          {/* 下方圆点指示器 */}
          <View style={styles.dotsBox}>
            {articleDetail?.images.map((_, index) => (
              <View
                style={[styles.dot, activeIndex === index && styles.activeDot]}
                key={index}
              ></View>
            ))}
          </View>
        </View>
        {/* 文章详情 */}
        <View style={styles.detailLayout}>
          <Text style={styles.title}>{articleDetail?.title}</Text>
          <Text style={styles.desc}>{articleDetail?.desc}</Text>
          <View style={styles.tagBox}>
            {articleDetail?.tag.map(item => (
              <Text style={styles.tagTxt} key={item}>
                #{item}
              </Text>
            ))}
          </View>
          <Text style={styles.locationTxt}>
            {articleDetail?.dateTime} {articleDetail?.location}
          </Text>
        </View>
        {/* 评论 */}
        <View style={styles.commentsContainer}>
          <Text style={styles.commentCountTxt}>
            {comment?.length ? `共${comment?.length}条评论` : '暂无评论'}
          </Text>
          {/* 个人头像和输入框 */}
          <View style={styles.avatarAndInput}>
            <Image source={{ uri: userStore.userInfo.avatar }} style={styles.myAvatar}></Image>
            <TextInput placeholder="说点什么吧，万一火了呢~" style={styles.myInput}></TextInput>
          </View>
          {/* 评论列表 */}
          <View style={styles.commentListContainer}>
            {comment?.map((item, index) => (
              <View key={`${item.avatarUrl}-${index}`} style={{ width: '100%' }}>
                <Comment comment={item}></Comment>
              </View>
            ))}
          </View>
        </View>
      </ScrollView>

      {/* 底部 */}
      <View style={styles.footer}>
        {/* 输入框 */}
        <View style={styles.inputView}>
          <TextInput
            style={styles.input}
            placeholder="说点什么..."
            placeholderTextColor="#333"
            onFocus={onFocus}
            onBlur={onBlur}
          ></TextInput>
          <Image source={icon_edit_comment} style={styles.iconEdit}></Image>
        </View>
        {/* 右侧图标 */}
        {footerRightShow && (
          <View style={styles.footerRightLayout}>
            <View style={styles.iconBox}>
              <HeartAnimated selected={articleDetail?.isFavorite!} size={30}></HeartAnimated>
              <Text style={styles.countTxt}>{articleDetail?.favoriteCount}</Text>
            </View>
            <View style={styles.iconBox}>
              <Image
                source={articleDetail?.isCollection ? icon_collection_selected : icon_collection}
                style={styles.iconFooter}
              ></Image>
              <Text style={styles.countTxt}>{articleDetail?.favoriteCount}</Text>
            </View>
            <View style={styles.iconBox}>
              <Image source={icon_comment} style={styles.iconFooter}></Image>
              <Text style={styles.countTxt}>{articleDetail?.comments.length}</Text>
            </View>
          </View>
        )}
      </View>
    </View>
  )
})

export default Article

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
    backgroundColor: '#fff'
  },
  header: {
    width: '100%',
    height: 60,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 15
  },
  iconArrow: {
    width: 28,
    height: 28,
    resizeMode: 'contain'
  },
  avatar: {
    width: 42,
    height: 42,
    borderRadius: 21
  },
  nameAvatarLayout: {
    flexDirection: 'row',
    height: '100%',
    alignItems: 'center',
    marginLeft: 15,
    flex: 1
  },
  username: {
    fontSize: 16,
    marginLeft: 10
  },
  followBtn: {
    width: 62,
    height: 32,
    borderColor: '#d9b3c1',
    borderWidth: 1,
    borderRadius: 20,
    alignItems: 'center',
    justifyContent: 'center'
  },
  followTxt: {
    fontSize: 14,
    color: '#f92845'
  },
  iconShare: {
    width: 34,
    height: 34,
    marginLeft: 12
  },
  swiperContainer: {
    width: '100%',
    height: 500,
    position: 'relative'
  },
  imageView: {
    width: '100%',
    height: '100%',
    resizeMode: 'cover'
  },
  pageBox: {
    position: 'absolute',
    top: 20,
    right: 16,
    width: 45,
    height: 26,
    backgroundColor: '#353637',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 13
  },
  pageTxt: {
    color: '#fff'
  },
  dotsBox: {
    position: 'absolute',
    bottom: 20,
    flexDirection: 'row',
    width: '100%',
    justifyContent: 'center'
  },
  dot: {
    width: 6,
    height: 6,
    borderRadius: 3,
    backgroundColor: '#cbcbcb',
    marginHorizontal: 3
  },
  activeDot: {
    backgroundColor: '#f92845'
  },
  detailLayout: {
    paddingHorizontal: 18,
    borderBottomColor: '#f6f6f6',
    borderBottomWidth: 1
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold'
  },
  desc: {
    fontSize: 17,
    marginTop: 10
  },
  tagBox: {
    width: '100%',
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginTop: 8
  },
  tagTxt: {
    color: '#31405a',
    marginRight: 8
  },
  locationTxt: {
    color: '#999',
    marginTop: 15,
    marginBottom: 20
  },
  footer: {
    width: '100%',
    height: 66,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 10,
    borderTopColor: '#f6f6f6',
    borderTopWidth: 1
  },
  inputView: {
    flex: 1,
    height: 50,
    backgroundColor: '#f6f6f6',

    borderRadius: 25
  },
  input: {
    height: '100%',
    width: '100%',
    paddingRight: 20,
    paddingLeft: 38,
    fontSize: 16
  },
  footerRightLayout: {
    marginLeft: 10,
    flexDirection: 'row',
    justifyContent: 'space-between',
    gap: 10
  },
  iconEdit: {
    position: 'absolute',
    width: 24,
    height: 24,
    left: 6,
    top: 12
  },
  iconBox: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  countTxt: {
    fontSize: 16,
    fontWeight: 'bold',
    marginLeft: 2
  },
  iconFooter: {
    width: 30,
    height: 30,
    resizeMode: 'contain'
  },
  commentsContainer: {
    width: '100%'
  },
  commentCountTxt: {
    color: '#828282',
    marginLeft: 15,
    marginTop: 24
  },
  avatarAndInput: {
    width: '100%',
    paddingHorizontal: 20,
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 12
  },
  myAvatar: {
    width: 36,
    height: 36,
    resizeMode: 'contain',
    borderRadius: 20
  },
  myInput: {
    flex: 1,
    height: 40,
    backgroundColor: '#f5f5f5',
    borderRadius: 20,
    marginLeft: 10,
    paddingHorizontal: 20
  },
  commentListContainer: {
    width: '100%',
    marginTop: 23
  }
})
